//
//  LVPhotoBrowserCollectionViewCell.swift
//  PhotoBrowser
//
//  Created by 刘伟 on 16/4/28.
//  Copyright © 2016年 刘伟. All rights reserved.
//

import UIKit
import SDWebImage

class LVPhotoBrowserCollectionViewCell: UICollectionViewCell {
    
    
    lazy var imageV = UIImageView()
    
    var shop : LVShop? {
        didSet{
            
            //            1.nil值校验
            guard let urlstring = shop?.q_pic_url else{
                return
            }
            
            //            2.获取小图
            var smallImage = SDWebImageManager.sharedManager().imageCache.imageFromMemoryCacheForKey(urlstring)
            
            if smallImage == nil {
                smallImage = UIImage(named: "empty_picture")
            }
            
            //            3.计算imageV的frame
            imageV.frame = calculateFrame(smallImage)
            
            //            4.设置大图
            guard let urlstr = shop?.z_pic_url else {
                return
            }
            let url = NSURL(string: urlstr)
            
            //            5.设置图片,当大图下载完毕后修改图片的frame
            imageV.sd_setImageWithURL(url, placeholderImage: smallImage) { (image :UIImage!, _ , _ , _ ) -> Void in
                self.imageV.frame = self.calculateFrame(image)
                
            }
        }
    }
    
    //    构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setUpUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}



// MARK: - 计算imageV的大小
extension LVPhotoBrowserCollectionViewCell{
    func calculateFrame (image: UIImage) -> CGRect{
    
        let x : CGFloat = 0.0
        let width : CGFloat = UIScreen.mainScreen().bounds.width
        let height : CGFloat = image.size.height * width / image.size.width
        let y : CGFloat = (UIScreen.mainScreen().bounds.height - height) * 0.5

        return CGRectMake(x, y, width, height)
    }

}


// MARK: - 设置UI
extension LVPhotoBrowserCollectionViewCell{
    func setUpUI(){
        contentView.addSubview(imageV)
    }
}

